package com.etooling.germa.controller;

import com.etooling.framework.entity.ImportDataBatch;
import com.etooling.framework.entity.AttachFile;
import com.etooling.framework.jpa.JpaQueryBuilder;
import com.etooling.framework.jpa.Specifications;
import com.etooling.framework.repository.FileResourceRepository;
import com.etooling.framework.repository.AttachFileRepository;
import com.etooling.framework.repository.ImportDataBatchRepository;
import com.etooling.framework.repository.EmployeeRepository;
import com.etooling.germa.entity.ImportBomDetails;
import com.etooling.germa.repository.ImportBomDetailsRepository;
import com.etooling.germa.service.ImportBomService;
import com.etooling.germa.thread.UploadBomExcelThread;
import com.etooling.framework.service.FileUploadSaveService;
import com.etooling.framework.utils.WebUtils;
import com.etooling.framework.entity.Employee;
import com.etooling.framework.entity.FileResource;
import com.etooling.framework.svo.ReplyObj;
import com.etooling.pdm.entity.Bom;
import com.etooling.pdm.entity.BomDetail;
import com.etooling.pdm.repository.BomDetailRepository;
import com.etooling.pdm.repository.BomRepository;
import com.etooling.pdm.repository.GoodsSpecsRepository;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.WorkbookFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import java.io.InputStream;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

@RestController
@RequestMapping("/admin/germa/bom")
public class ImportBomController {

    @Autowired
    private FileResourceRepository fileResourceRepository;

    @Autowired
    private AttachFileRepository attachFileRepository;

    @Autowired
    private ImportDataBatchRepository importDataBatchRepository;

    @Autowired
    private EmployeeRepository employeeRepository;

    @Autowired
    private ImportBomService importBomService;

    @Autowired
    private BomRepository bomRepository;

    @Autowired
    private ImportBomDetailsRepository importBomDetailsRepository;

    @Autowired
    private BomDetailRepository bomDetailRepository;

    @Autowired
    private GoodsSpecsRepository goodsSpecsRepository;

    //imp_data_bach  表查询
    @RequestMapping("impDataBachPageQuery")
    @ResponseBody
    ReplyObj impDataBachPageQuery(HttpServletRequest request,
                                  @RequestParam(defaultValue = "", required = false, value = "importDataBatchId") String importDataBatchId
    ) {
        System.out.println(importDataBatchId);
        List<ImportBomDetails> importBomDetailsList = importBomDetailsRepository.getByImportDataBatchId(importDataBatchId);
        Integer ResultMemoCount = importBomDetailsRepository.getResultMemoCount(importDataBatchId);
        HashMap<String, Object> stringObjectHashMap = new HashMap<>();
        stringObjectHashMap.put("importBomDetailsList", importBomDetailsList);
        stringObjectHashMap.put("ResultMemoCount", ResultMemoCount);
        return WebUtils.flushSuccess(stringObjectHashMap);
    }

    //插入bom && bomDetails
    @RequestMapping("UpdateBomDetails")
    @ResponseBody
    ReplyObj UpdateBomDetails(HttpServletRequest request,
                              @RequestParam(defaultValue = "", required = false, value = "importDataBatchId") String importDataBatchId,
                              @RequestParam(defaultValue = "", required = false, value = "specsId") String specsId) {

        ImportDataBatch importDataBatch = importDataBatchRepository.findById(importDataBatchId).orElse(null);
        String loginId = WebUtils.getSessionValue(request, WebUtils.LOGIN_USER_KEY);
        String companyId = WebUtils.getSessionValue(request, WebUtils.LOGIN_COMPANY_ID_KEY);
        Employee one = employeeRepository.getOne(loginId);
        if (importDataBatch == null) {
            // 处理importDataBatch不存在的情况
            return WebUtils.flushFailure("无法找到与给定ID匹配的ImportDataBatch");
        }
        // 根据specsId查询所有相关的BOM并禁用它们
        List<Bom> relatedBoms = bomRepository.findByGoodsSpecsId(specsId);
        for (Bom bom : relatedBoms) {
            bom.setStatus(Bom.STATUS_DISABLE);
        }
        bomRepository.saveAll(relatedBoms);
        Bom bom = new Bom();
        bom.setBomName(importDataBatch.getBomName());
        bom.setMemo(importDataBatch.getMemo());
        bom.setGoodsSpecs(goodsSpecsRepository.getById(importDataBatch.getGoodsSpecsId()));
        bom.setStatus(Bom.STATUS_RUN);
        bom.setCreateTime(new Date());
        bom.setCreateUserId(loginId);
        bom.setCompanyId(companyId);
        bom.setBatchId(importDataBatch.getId());
        bom.setCreateUserName(one.getName());
        bomRepository.save(bom);


        //根据临时bomId拿到零时BomDetails的数据
//        importBomDetailsRepository.updateDetails(importDataBatchId);
        importBomDetailsRepository.updateDetails(importDataBatchId,bom.getId(),companyId);
        importBomDetailsRepository.updateGoodsSpecsId(bom.getId());


        BomDetail bomDetail = new BomDetail();
        bomDetail.setCompanyId((companyId));
        bomDetailRepository.save(bomDetail);
        return WebUtils.flushSuccess();
    }


    @RequestMapping("/uploadBomExcel")
    @ResponseBody
    public ReplyObj uploadBomExcel(HttpServletRequest request,
                                   @RequestParam(defaultValue = "", required = false, value = "loginId") String loginId,
                                   @RequestParam(defaultValue = "", required = false, value = "companyId") String companyId,
                                   @RequestParam(defaultValue = "", required = false, value = "bomName") String bomName,
                                   @RequestParam(defaultValue = "", required = false, value = "bomMemo") String bomMemo,
                                   @RequestParam(defaultValue = "", required = false, value = "specsId") String specsId) {

        MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request;
        MultipartFile uploadFile = multiRequest.getFile("uploadFiles");
        if (uploadFile != null && !uploadFile.isEmpty()) {
            Boolean isEncrypt = false;
            try {
                if (WebUtils.checkStr(request.getParameter("isEncrypt"))) {
                    isEncrypt = Boolean.valueOf(request.getParameter("isEncrypt"));
                }

                // 获取文件存储方式
                FileResource fileResource = fileResourceRepository.getByApplyResource("七牛存储");
                String uploadImplClass = fileResource.getImplClassName();
                FileUploadSaveService fileUploadSaveService = (FileUploadSaveService) Class.forName(uploadImplClass).getDeclaredConstructor().newInstance();
                AttachFile attachFile = fileUploadSaveService.upload(attachFileRepository, uploadFile, fileResource, isEncrypt);

                ImportDataBatch importDataBatch = new ImportDataBatch();
                importDataBatch.setFileName(attachFile.getName());
                importDataBatch.setAttachFile(attachFile);
                importDataBatch.setCreateTime(new Date());
                importDataBatch.setMemo(bomMemo);
                importDataBatch.setBomName(bomName);
                importDataBatch.setGoodsSpecsId(specsId);

                importDataBatch.setFileType(ImportDataBatch.TYPE_IMPORT_BOM);
                importDataBatch.setStatus(ImportDataBatch.STATUS_SUBMIT_DOING);
                ImportDataBatch savedBatch = importDataBatchRepository.save(importDataBatch);

                // 启动处理线程
                UploadBomExcelThread uploadBomExcelThread = new UploadBomExcelThread(importBomService, savedBatch, loginId, companyId, bomName, bomMemo, specsId);
                uploadBomExcelThread.start();

                //   临时表查询出来
                while (savedBatch.getStatus().equals(ImportDataBatch.STATUS_SUBMIT_DOING)) {
                    //主线程休眠2秒
                    Thread.sleep(1000);
                }

                // 如果文件处理成功，返回成功消息
                return WebUtils.flushObjSuccess(savedBatch);

            } catch (IllegalArgumentException e) {
                e.printStackTrace();
                return WebUtils.flushFailure(e.getMessage());

            } catch (Exception e) {
                e.printStackTrace();
                return WebUtils.flushFailure("文件上传失败，请重新选择文件进行提交上传");
            }
        }

        return WebUtils.flushFailure("文件上传失败，请重新选择文件进行提交上传");
    }
}
